package com.bamboo.framework.common.qiniu.kodo.config;

import com.bamboo.framework.common.qiniu.kodo.enums.KodoRegionalType;
import com.qiniu.common.Zone;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import javax.annotation.Resource;
import jodd.util.StringUtil;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * @Author: GuoQing
 * @Date: 2019/1/29 14:44
 * @description 千牛云对象储存配置类
 */
@Data
@Configuration
public class KodoProperties {

  @Resource
  BucketProperties bucketProperties;

  /**
   * 千牛云accessKey
   */
  @Value("${qiniu.accessKey:}")
  private String accessKey;
  /**
   * 千牛云secretKey
   */
  @Value("${qiniu.secretKey:}")
  private String secretKey;

  public Zone getZone(String regional) {
    return KodoRegionalType.getZoneByName(regional);
  }

  /**
   * 获取上传token
   */
  public String getUpToken(String bucket) {
    Auth auth = Auth.create(accessKey, secretKey);
    String upToken = auth.uploadToken(bucket);
    return upToken;
  }


  public UploadManager getUploadManager(String regional) {
    com.qiniu.storage.Configuration cfg = new com.qiniu.storage.Configuration(
        this.getZone(regional));
    return new UploadManager(cfg);
  }

  /**
   * 获取要上传的桶，默认为配置文件中配置的
   * @param bucketProperties 桶信息
   */
  public BucketProperties getBucket(BucketProperties bucketProperties) {
    if (bucketProperties == null) {
      if (this.bucketProperties != null ) {
        bucketProperties =this.bucketProperties;
      } else {
        return new BucketProperties();
      }
    }
    if (StringUtil.isEmpty(bucketProperties.getRegional())) {
      return null;
    }
    if (StringUtil.isEmpty(bucketProperties.getName())) {
      return null;
    }
    if (StringUtil.isEmpty(bucketProperties.getDomain())) {
      return null;
    }
    bucketProperties.setUpToken(getUpToken(bucketProperties.getName()));
    bucketProperties.setUploadManager(getUploadManager(bucketProperties.getRegional()));
    return bucketProperties;
  }
}
